package com.alisonyu.spider.Router;

import com.alisonyu.spider.Proccessor.Context;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.function.Consumer;

/**
 * Created by yu on 2017/9/22.
 */
public class Router
{
    private LinkedList<Route> routesList=new LinkedList<>();

    //默认的处理器，当所有的路由都不匹配的时候就会调用该处理器
    private Consumer<Context> defaultHandler;

    public Router(){
        this.defaultHandler=(html -> {});
    }


    public Route route(){
        Route route=new Route();
        routesList.offer(route);
        return route;
    }

    public Iterator<Route> RoutesIterator(){
        return routesList.iterator();
    }

    public void setDefaultHandler(Consumer<Context> defaultHandler){
        this.defaultHandler=defaultHandler;
    }

    //将会调用第一个匹配的路由注册的handler
    void accept(Context context){
        for(Route route:routesList){
            if(route.match(context.getRequest().getUrl(),context.getResponse().getContent())){
                route.handle(context);
                return;
            }
        }
        //当所有的路由都不匹配的时候就会调用该处理器
        defaultHandler.accept(context);
    }





}
